package top.jacktgq.itheima.netty.protocol_design.groupchat.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import top.jacktgq.itheima.netty.protocol_design.groupchat.message.Message;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.session.SessionFactory;

/**
 * @Author CandyWall
 * @Date 2022/2/26--14:15
 * @Description
 */
@Slf4j
@ChannelHandler.Sharable
/**
 * 服务器端聊天消息处理
 */
public class ServerMessageHandler extends SimpleChannelInboundHandler<Message> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        // 获取用户的消息
        log.debug("客户端消息：{}", msg);
        // 根据消息的类型来各自做不同的处理
        msg.handle(ctx);
    }

    @Override
    // 当连接断开时会触发
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String username = SessionFactory.getSession().getUsernameByChannel(ctx.channel());
        SessionFactory.getSession().unbind(ctx.channel());
        log.debug("{} - {} 已经断开", username, ctx.channel());
    }

    @Override
    // 发生异常
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        String username = SessionFactory.getSession().getUsernameByChannel(ctx.channel());
        SessionFactory.getSession().unbind(ctx.channel());
        log.debug("发生异常，{} - {} 已经断开", username, ctx.channel());
        cause.printStackTrace();
    }
}
